package com.hxzy.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hxzy.common.dto.ChangeStatusDTO;
import com.hxzy.common.enums.AckCode;
import com.hxzy.dto.DishFlavorDTO;
import com.hxzy.dto.ProductDishFlavorDTO;
import com.hxzy.dto.ProductSearchDTO;
import com.hxzy.entity.DishFlavor;
import com.hxzy.entity.Merchandise;
import com.hxzy.exception.ServiceException;
import com.hxzy.mapper.MerchandiseMapper;
import com.hxzy.service.DishFlavorService;
import com.hxzy.service.ProductService;
import com.hxzy.vo.ProductDishFlavorVO;
import com.hxzy.vo.ProductVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 商品信息
 * @author Administrator
 */
@Service
public class ProductServiceImpl extends ServiceImpl<MerchandiseMapper,Merchandise> implements ProductService {

    /**
     * 口味表的操作
     */
    @Autowired
    private DishFlavorService dishFlavorService;

   @Override
    public List<ProductVO> search(ProductSearchDTO productSearchDTO) {
        return super.getBaseMapper().search(productSearchDTO);
    }

    /**
     * 新装操作影响2个表 (merchandise商品表， dish_flavor口味表)
     * @param productDishFlavorDTO
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean add(ProductDishFlavorDTO productDishFlavorDTO) {
       //商品表保存
        Merchandise  product=new Merchandise();
        BeanUtils.copyProperties(productDishFlavorDTO,product);
        boolean save = this.save(product);

        if(save){
            //口味表的保存
            productDishFlavorDTO.setId(product.getId());
            saveDishFlavor(productDishFlavorDTO);
        }

        return save;
    }

    private void saveDishFlavor(ProductDishFlavorDTO productDishFlavorDTO) {
        List<DishFlavorDTO> dishFlavors = productDishFlavorDTO.getDishFlavors();
        if(dishFlavors!=null && dishFlavors.size()>0){
            for(DishFlavorDTO  dto : dishFlavors){

                DishFlavor dishFlavor=new DishFlavor();
                //商品ID
                dishFlavor.setDishId(productDishFlavorDTO.getId());
                dishFlavor.setName( dto.getName());
                // java [] -->  json字符串
                String jsonValue= JSONUtil.toJsonStr(dto.getValue());
                dishFlavor.setValue(jsonValue);
                dishFlavor.setIsDeleted(0);

                this.dishFlavorService.save(dishFlavor);
            }
        }
    }

    /**
     * 修改
     * @param productDishFlavorDTO
     * @return
     */
    @Override
    public boolean edit(ProductDishFlavorDTO productDishFlavorDTO) {
        Merchandise db = this.getById(productDishFlavorDTO.getId());
        if(db==null){
            throw new ServiceException(AckCode.NOT_FOUND_DATA);
        }

        if(!db.getMerchantId().equals(productDishFlavorDTO.getMerchantId())){
            throw new ServiceException(AckCode.VALUE_NOT_CHANGE);
        }

        //复制数据
        db.setCategoryId(productDishFlavorDTO.getCategoryId());
        db.setPicture(productDishFlavorDTO.getPicture());
        db.setDescription(productDishFlavorDTO.getDescription());
        db.setIsgrounding(productDishFlavorDTO.getIsgrounding());
        db.setName(productDishFlavorDTO.getName());
        db.setPrice(productDishFlavorDTO.getPrice());

        boolean result = this.updateById(db);
        if(result){
            //先删除所有的口味列表(mybatis-plus写法) delete from Dish_Flavor where dish_id=?
            QueryWrapper<DishFlavor> queryWrapper=new QueryWrapper();
            queryWrapper.eq("dish_id",productDishFlavorDTO.getId());
            this.dishFlavorService.remove(queryWrapper);

            //再新增口味列表
            //口味表的保存
            saveDishFlavor(productDishFlavorDTO);
        }
        return result;
    }

    @Override
    public boolean changeStatus(ChangeStatusDTO changeStatusDTO) {

        return this.baseMapper.changeStatus(changeStatusDTO.getId(),changeStatusDTO.getStatus())>0;
    }

    /**
     * 根据主键查询数据
     * @param id
     * @return
     */
    @Override
    public ProductDishFlavorVO findById(Long id) {
        // 查询商品表
        Merchandise dbMer = this.getBaseMapper().selectByPrimaryKey(id);
        if(dbMer==null){
            throw new ServiceException(AckCode.NOT_FOUND_DATA);
        }

        //查询dish_flavor表的数据
        List<DishFlavor> arrDishFlavor=this.dishFlavorService.selectByDishId(dbMer.getId());

        //组成自定义对象
        ProductDishFlavorVO  resultVO=new ProductDishFlavorVO();
        BeanUtils.copyProperties(dbMer, resultVO);

        if(arrDishFlavor!=null && arrDishFlavor.size()>0){
            //把数据库DishFlavor口味对象，转换在自定义的DishFlavorDTO
           List<DishFlavorDTO>  dtoList=new ArrayList<>();
           for(DishFlavor  df : arrDishFlavor){
               DishFlavorDTO  dto=new DishFlavorDTO();
               dto.setName(df.getName());
               //数据库 "[\"不辣\",\"微辣\",\"中辣\",\"重辣\"]"
               String values=df.getValue();
               //字符串--> java [] -->json反序列化
               List<String> stringList = JSONUtil.toList(values, String.class);
               //把集合转换成数组
               String[] strings = stringList.toArray(new String[0]);
               dto.setValue(strings);

               //为了给前端 Element-ui的 tags动态组件使用
               dto.setInputValue("");
               dto.setInputVisible(false);
               dtoList.add(dto);
           }
           resultVO.setDishFlavors(dtoList);
        }

        return resultVO;
    }

    /**
     * 根据商家ID和分类的ID查询菜品列表
     * @param categoryId
     * @param merchantId
     * @return
     */
    @Override
    public List<ProductDishFlavorVO> searchByCategoryAndMerchant(Long categoryId, Long merchantId) {
        List<Merchandise> merchandisesList = this.getBaseMapper().searchByCategoryAndMerchant(categoryId, merchantId);

        //组装商品
        List<ProductDishFlavorVO>  arrDishList=new ArrayList<>();

        if(merchandisesList.size()>0){
            for (Merchandise m : merchandisesList ) {
               ProductDishFlavorVO  productDishFlavorVO=new ProductDishFlavorVO();
               BeanUtils.copyProperties( m, productDishFlavorVO);
               //查询对应口味
                List<DishFlavor> dbFlavors = this.dishFlavorService.selectByDishId(m.getId());
                if(dbFlavors.size()>0){
                    List<DishFlavorDTO> dishList=new ArrayList<>();
                    for(DishFlavor db: dbFlavors){
                        DishFlavorDTO dto=new DishFlavorDTO();
                        dto.setName(db.getName());
                        //数据库 "[\"不辣\",\"微辣\",\"中辣\",\"重辣\"]"
                        String values=db.getValue();
                        //字符串--> java [] -->json反序列化
                        List<String> stringList = JSONUtil.toList(values, String.class);
                        //把集合转换成数组
                        String[] strings = stringList.toArray(new String[0]);
                        dto.setValue(strings);
                        dishList.add(dto);
                    }
                    productDishFlavorVO.setDishFlavors(dishList);
                }
                arrDishList.add(productDishFlavorVO);
            }
        }

        return arrDishList;
    }


}
